// pages/pay/pay.js
const api = require('../../utils/api.js');

Page({
  data: {
    plan: null,
    isProcessing: false,
    paymentMethods: [
      {
        id: 'wechat',
        name: '微信支付',
        icon: '/static/images/wechat-pay.png',
        selected: true
      },
      {
        id: 'alipay',
        name: '支付宝',
        icon: '/static/images/alipay.png',
        selected: false
      }
    ],
    selectedPayment: 'wechat',
    memberStatus: {
        isVip: false,
        expireDate: null,
        memberType: 'normal'
    }
  },

  onLoad: function (options) {
    console.log('支付页面加载');
    
    // 接收从会员页面传递的套餐信息
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('acceptPlanData', (data) => {
      console.log('接收套餐信息:', data.plan);
      this.setData({
        plan: data.plan
      });
    });

    // 拉取会员状态
    this.fetchMemberStatus();
  },

  fetchMemberStatus: function() {
    const that = this;
    myRequest({
      url: api.getUserInfo, // 这里和 login.js 里一致
      method: 'GET'
    }).then(res => {
      that.setData({
        memberStatus: {
          isVip: res.data.isVip,
          expireDate: res.data.expireDate,
          memberType: res.data.memberType
        }
      });
    });
  },

  // 选择支付方式
  selectPayment: function(e) {
    const paymentId = e.currentTarget.dataset.paymentId;
    console.log('选择支付方式：', paymentId); // 新增
    
    // 更新支付方式选择状态
    const paymentMethods = this.data.paymentMethods.map(method => {
      method.selected = method.id === paymentId;
      return method;
    });

    this.setData({
      paymentMethods: paymentMethods,
      selectedPayment: paymentId
    });
  },

  // 确认支付
  confirmPayment: function() {
    if (!this.data.plan) {
      wx.showToast({
        title: '套餐信息错误',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    if (this.data.isProcessing) {
      return;
    }

    this.setData({
      isProcessing: true
    });

    wx.showLoading({
      title: '正在支付...'
    });

    // 模拟支付过程
    setTimeout(() => {
      this.processPayment();
    }, 1500);
  },

  // 处理支付
  processPayment: function() {
    // 模拟支付成功
    const paymentData = {
      memberType: 'vip',
      duration: this.data.plan.duration,
      planId: this.data.plan.id,
      price: this.data.plan.currentPrice,
      paymentMethod: this.data.selectedPayment
    };

    // 只用mockPaymentAPI，不调用api.activateMember
    this.mockPaymentAPI(paymentData).then(res => {
      wx.hideLoading();
      this.setData({
        isProcessing: false
      });

      console.log('支付成功:', res);

      wx.showModal({
        title: '支付成功',
        content: `恭喜您成功开通${this.data.plan.name}！\n支付金额：¥${this.data.plan.currentPrice}\n有效期至：${res.expireDate}`,
        showCancel: false,
        confirmText: '好的',
        success: () => {
          // 设置本地缓存，前端立即显示会员状态
          wx.setStorageSync('isVip', true);
          wx.setStorageSync('vipExpireDate', res.expireDate); // 新增：保存到期时间
          // 跳转到“我的”页面
          wx.switchTab({
            url: '/pages/profile/profile'
          });
        }
      });

    }).catch(err => {
      wx.hideLoading();
      this.setData({
        isProcessing: false
      });

      console.error('支付失败:', err);

      wx.showModal({
        title: '支付失败',
        content: err.message || '网络异常，请稍后重试',
        showCancel: false,
        confirmText: '知道了'
      });
    });
  },

  // 模拟支付API
  mockPaymentAPI: function(paymentData) {
    return new Promise((resolve, reject) => {
      // 模拟网络延迟
      setTimeout(() => {
        // 模拟90%成功率
        if (Math.random() > 0.1) {
          // 支付成功
          const expireDate = new Date();
          expireDate.setMonth(expireDate.getMonth() + paymentData.duration);
          
          resolve({
            success: true,
            orderId: 'ORDER_' + Date.now(),
            expireDate: expireDate.toLocaleDateString(),
            message: '支付成功'
          });
        } else {
          // 支付失败
          reject({
            success: false,
            message: '支付失败，请重试'
          });
        }
      }, 1000);
    });
  },

  // 返回上一页
  goBack: function() {
    wx.navigateBack();
  },

  // 查看套餐详情
  showPlanDetail: function() {
    if (!this.data.plan) return;
    
    wx.showModal({
      title: this.data.plan.name + '详情',
      content: this.data.plan.features.join('\n'),
      showCancel: false,
      confirmText: '我知道了'
    });
  }
}); 